package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.place;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.dao.models.IncomeRatioContent;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.mng.dto.place.PlaceUser;
import com.gzhryc.shared_device.oem.h5.agent.mng.dto.place.PlaceUserIncomeRatio;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PlaceUserController {

    @Route(value = "/place/user/list.data")
    public ListResult<PlaceUser> listData(HttpServletRequest request) {
        ListResult<PlaceUser> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long placeId = WebUtils.getLong(request, "placeId");
        if (placeId != null) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
                if (physicalStore != null && physicalStore.getUserId().equals(loginUser.getId())) {
                    List<PlaceProfitUser> placeProfitUserList = PlaceProfitUserService.self().findJoinByPlaceId(placeId);

                    Map<String, Double> incomeRatioData = new HashMap<>();
                    result.setCode(DtoConstants.SUCCESS, null);
                    result.getBody().setData(new ArrayList<>());

                    PlaceUser placeUser = new PlaceUser();
                    placeUser.setUserId(loginUser.getId());
                    placeUser.setUserName(loginUser.getName());
                    placeUser.setUserPhone(loginUser.getPhone());
                    placeUser.setRoleType(ERoleType.Agent.index());
                    placeUser.setRoleTypeName(ERoleType.Agent.note());
                    placeUser.setCanUpdate(false);
                    placeUser.setIncomeRatioItems(new ArrayList<>());
                    result.getBody().getData().add(placeUser);

                    if (placeProfitUserList != null && placeProfitUserList.size() > 0) {
                        for (PlaceProfitUser profitUser : placeProfitUserList) {
                            PlaceUser userItem = new PlaceUser();
                            userItem.setUserId(profitUser.getUserId());
                            userItem.setUserName(profitUser.getUser().getName());
                            userItem.setUserPhone(profitUser.getUser().getPhone());
                            userItem.setRoleType(profitUser.getRoleType());
                            userItem.setRoleTypeName(profitUser.getRoleTypeName());
                            userItem.setNote(profitUser.getNote());

                            if (StringTools.isNotBlank(profitUser.getIncomeRatioContent())) {
                                userItem.setIncomeRatioItems(new ArrayList<>());
                                IncomeRatioContent incomeRatioContent = JsonTools.fromJson(profitUser.getIncomeRatioContent(), IncomeRatioContent.class);
                                for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                                    PlaceUser.IncomeRatioItem incomeRatioItem = new PlaceUser.IncomeRatioItem();
                                    incomeRatioItem.setBusinessType(item.getBusinessType());
                                    incomeRatioItem.setBusinessTypeName(EBusinessType.note(item.getBusinessType()));
                                    incomeRatioItem.setIncomeRatio(item.getIncomeRatio());
                                    userItem.getIncomeRatioItems().add(incomeRatioItem);

                                    Double incomeRatio = incomeRatioData.get(item.getBusinessType());
                                    if (incomeRatio == null) {
                                        incomeRatio = 0.0;
                                    }
                                    incomeRatio = incomeRatio + item.getIncomeRatio();
                                    incomeRatioData.put(item.getBusinessType(), incomeRatio);
                                }
                            }
                            result.getBody().getData().add(userItem);
                        }
                    }

                    if (incomeRatioData.size() > 0) {
                        if (placeUser.getIncomeRatioItems() == null) {
                            placeUser.setIncomeRatioItems(new ArrayList<>());
                        }

                        //未部署设备时
                        for (String businessType : incomeRatioData.keySet()) {
                            boolean flag = true;
                            for (PlaceUser.IncomeRatioItem item : placeUser.getIncomeRatioItems()) {
                                if (businessType.equals(item.getBusinessType())) {
                                    flag = false;
                                    break;
                                }
                            }

                            if (flag) {
                                PlaceUser.IncomeRatioItem incomeRatioItem = new PlaceUser.IncomeRatioItem();
                                incomeRatioItem.setBusinessType(businessType);
                                incomeRatioItem.setBusinessTypeName(EBusinessType.note(businessType));
                                incomeRatioItem.setIncomeRatio(100D);

                                Double incomeRatio = incomeRatioData.get(businessType);
                                if (incomeRatio != null) {
                                    Double temp = 100.0 - incomeRatio;
                                    if (temp > 0) {
                                        incomeRatioItem.setIncomeRatio(temp);
                                    } else {
                                        incomeRatioItem.setIncomeRatio(0D);
                                    }
                                }
                                placeUser.getIncomeRatioItems().add(incomeRatioItem);
                            }
                        }
                    }
                }else{
                    result.setCode(DtoConstants.NOT_POWER,"无权限查看");
                }
            }
        }
        return result;
    }

    @Route(value = {"/place/user/add.html"})
    public String add(HttpServletRequest request) {
        String businessType = WebUtils.getString(request,"businessType");
        if(StringTools.isNotBlank(businessType)){
            request.setAttribute("businessTypeName",EBusinessType.note(businessType));
        }else {
            List<EBusinessType> businessTypeList = new ArrayList<>();
            businessTypeList.add(EBusinessType.CDB);
            businessTypeList.add(EBusinessType.CDCZ);
            businessTypeList.add(EBusinessType.BXSCN);
            businessTypeList.add(EBusinessType.BXSCN_SHOP);
            request.setAttribute("businessTypeList", businessTypeList);
        }
        List<ERoleType> roleTypeList = new ArrayList<>();
        roleTypeList.add(ERoleType.Partner);
        roleTypeList.add(ERoleType.Merchant);
        roleTypeList.add(ERoleType.Referrer);
        request.setAttribute("roleTypeList", roleTypeList);
        return "/place/user/edit.html";
    }

    @Route(value = {"/place/user/add.do"})
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败，请稍后再试");
        PlaceProfitUser placeProfitUser = WebUtils.getParameter(request,PlaceProfitUser.class);
        String businessType = WebUtils.getString(request,"businessType");
        Double incomeRatio = WebUtils.getDouble(request,"incomeRatio");
        User user = WebUtils.getParameter(request,"user",User.class);
        if(placeProfitUser != null && user != null && StringTools.isNotBlank(user.getPhone())) {
            if (incomeRatio == null || incomeRatio < 0 || incomeRatio > 100) {
                result.setMsg("请填写正确的分成比例");
                return result;
            }

            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeProfitUser.getPlaceId());
                if (physicalStore == null) {
                    result.setMsg("网点不存在");
                    return result;
                }

                if (physicalStore.getUserId().equals(loginUser.getId())) {
                    User temp = UserService.self().getByPhone(user.getPhone());
                    if (temp != null) {
                        PlaceProfitUser profitUserTemp = PlaceProfitUserService.self().getByKeys(placeProfitUser.getPlaceId(), temp.getId());
                        if (profitUserTemp != null) {
                            IncomeRatioContent incomeRatioContent = null;
                            if (StringTools.isNotBlank(profitUserTemp.getIncomeRatioContent())) {
                                incomeRatioContent = JsonTools.fromJson(profitUserTemp.getIncomeRatioContent(), IncomeRatioContent.class);
                            }

                            if (incomeRatioContent == null) {
                                incomeRatioContent = new IncomeRatioContent();
                                IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                                item.setBusinessType(businessType);
                                item.setIncomeRatio(incomeRatio);
                                incomeRatioContent.getItems().add(item);
                            } else {
                                for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                                    if (item.getBusinessType().equals(businessType)) {
                                        item.setIncomeRatio(incomeRatio);
                                    }
                                }
                            }

                            try {
                                if (PlaceProfitUserService.self().updateNotNull(placeProfitUser, incomeRatioContent)) {
                                    result.setCode(DtoConstants.SUCCESS, null);
                                }
                            } catch (LogicException e) {
                                result.setMsg(e.getMessage());
                            }

                            return result;
                        }

                        if (physicalStore.getUserId().equals(temp.getId())) {
                            result.setMsg("用户已存在该网点中");
                            return result;
                        }
                    }

                    IncomeRatioContent incomeRatioContent = new IncomeRatioContent();
                    IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                    item.setBusinessType(businessType);
                    item.setIncomeRatio(incomeRatio);
                    incomeRatioContent.getItems().add(item);
                    
                    OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                    operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());
                    operateInfo.setOperatorId(loginUser.getId());

                    try {
                        if (PlaceProfitUserService.self().add(physicalStore,placeProfitUser, user, incomeRatioContent,operateInfo)) {
                            result.setCode(DtoConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        result.setMsg(e.getMessage());
                    }
                }else{
                    result.setCode(DtoConstants.NOT_POWER,"无权限操作");
                }
            }
        }
        return result;
    }

    @Route(value = {"/place/user/info.html"})
    public String info(HttpServletRequest request) {
        Long placeId = WebUtils.getLong(request,"placeId");
        Long userId = WebUtils.getLong(request,"userId");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
            if (physicalStore != null && physicalStore.getUserId().equals(loginUser.getId())) {
                PlaceProfitUser profitUser = PlaceProfitUserService.self().getJoinByKeys(placeId, userId);
                WebUtils.setAttribute(request, profitUser);
            }
        }
        return "/place/user/info.html";
    }

    @Route(value = {"/place/user/del.do"})
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        Long placeId = WebUtils.getLong(request,"placeId");
        Long userId = WebUtils.getLong(request,"userId");
        if(placeId != null && userId != null) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
                if (physicalStore != null && physicalStore.getUserId().equals(loginUser.getId())) {
                    try {
                        if (PlaceProfitUserService.self().deleteByKeys(placeId, userId)) {
                            result.setCode(DtoConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        result.setMsg(e.getMessage());
                    }
                }else{
                    result.setCode(DtoConstants.NOT_POWER,"无权限操作");
                }
            }
        }
        return result;
    }

    @Route(value = "/place/user/business_type/list.data")
    public ListResult<PlaceUserIncomeRatio> deviceFuncListData(HttpServletRequest request) {
        ListResult<PlaceUserIncomeRatio> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        Long placeId = WebUtils.getLong(request, "placeId");
        Long userId = WebUtils.getLong(request,"userId");
        if (placeId != null && userId != null) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
                if (physicalStore != null && physicalStore.getUserId().equals(loginUser.getId())) {
                    PlaceProfitUser placeProfitUser = PlaceProfitUserService.self().getByKeys(placeId, userId);
                    if (placeProfitUser != null && StringTools.isNotBlank(placeProfitUser.getIncomeRatioContent())) {
                        IncomeRatioContent incomeRatioContent = JsonTools.fromJson(placeProfitUser.getIncomeRatioContent(), IncomeRatioContent.class);
                        result.setCode(DtoConstants.SUCCESS, null);
                        result.getBody().setData(new ArrayList<>());
                        for (IncomeRatioContent.Item incomeRatioItem : incomeRatioContent.getItems()) {
                            PlaceUserIncomeRatio item = new PlaceUserIncomeRatio();
                            item.setBusinessType(incomeRatioItem.getBusinessType());
                            item.setBusinessTypeName(EBusinessType.note(incomeRatioItem.getBusinessType()));
                            item.setIncomeRatio(incomeRatioItem.getIncomeRatio());
                            result.getBody().getData().add(item);
                        }
                    }
                }else{
                    result.setCode(DtoConstants.NOT_POWER,"无权限查看");
                }
            }
        }
        return result;
    }

    @Route(value = {"/place/user/business_type/add.html"})
    public String deviceFuncAdd(HttpServletRequest request, HttpServletResponse response) {
        List<EBusinessType> businessTypeList = new ArrayList<>();
        businessTypeList.add(EBusinessType.CDB);
        businessTypeList.add(EBusinessType.CDCZ);
        businessTypeList.add(EBusinessType.BXSCN);
        businessTypeList.add(EBusinessType.BXSCN_SHOP);
        request.setAttribute("businessTypeList", businessTypeList);
        return "/place/user/business_type/edit.html";
    }

    @Route(value = {"/place/user/business_type/add.do"})
    public AjaxResult doDeviceFuncAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败，请稍后再试");
        PlaceProfitUser placeProfitUser = WebUtils.getParameter(request,PlaceProfitUser.class);
        String businessType = WebUtils.getString(request,"businessType");
        Double incomeRatio = WebUtils.getDouble(request,"incomeRatio");
        if(placeProfitUser != null && StringTools.isNotBlank(businessType) && placeProfitUser.getPlaceId() != null && placeProfitUser.getUserId() != null){
            if(incomeRatio == null || incomeRatio < 0 || incomeRatio > 100){
                result.setMsg("请填写正确的分成比例");
                return result;
            }

            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeProfitUser.getPlaceId());
                if (physicalStore != null && physicalStore.getUserId().equals(loginUser.getId())) {
                    PlaceProfitUser profitUserTemp = PlaceProfitUserService.self().getByKeys(placeProfitUser.getPlaceId(), placeProfitUser.getUserId());
                    if (profitUserTemp != null) {
                        IncomeRatioContent incomeRatioContent = null;
                        if (StringTools.isNotBlank(profitUserTemp.getIncomeRatioContent())) {
                            incomeRatioContent = JsonTools.fromJson(profitUserTemp.getIncomeRatioContent(), IncomeRatioContent.class);
                        }

                        if (incomeRatioContent == null) {
                            incomeRatioContent = new IncomeRatioContent();
                            IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                            item.setBusinessType(businessType);
                            item.setIncomeRatio(incomeRatio);
                            incomeRatioContent.getItems().add(item);
                        } else {
                            for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                                if (item.getBusinessType().equals(businessType)) {
                                    item.setIncomeRatio(incomeRatio);
                                }
                            }
                        }

                        try {
                            if (PlaceProfitUserService.self().updateNotNull(placeProfitUser, incomeRatioContent)) {
                                result.setCode(DtoConstants.SUCCESS, null);
                            }
                        } catch (LogicException e) {
                            result.setMsg(e.getMessage());
                        }
                    } else {
                        User user = UserService.self().getById(placeProfitUser.getUserId());
                        if (user == null) {
                            result.setMsg("未找到用户信息");
                            return result;
                        }
                        IncomeRatioContent incomeRatioContent = new IncomeRatioContent();
                        IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                        item.setBusinessType(businessType);
                        item.setIncomeRatio(incomeRatio);
                        incomeRatioContent.getItems().add(item);

                        OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                        operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());
                        operateInfo.setOperatorId(loginUser.getId());
                        
                        try {
                            if (PlaceProfitUserService.self().add(physicalStore,placeProfitUser, user, incomeRatioContent,operateInfo)) {
                                result.setCode(DtoConstants.SUCCESS, null);
                            }
                        } catch (LogicException e) {
                            result.setMsg(e.getMessage());
                        }
                    }
                }else {
                    result.setCode(DtoConstants.NOT_POWER,"无权限操作");
                }
            }
        }
        return result;
    }

    @Route(value = {"/place/user/business_type/update.html"})
    public String deviceFuncUpdate(HttpServletRequest request, HttpServletResponse response) {
        Long placeId = WebUtils.getLong(request,"placeId");
        Long userId = WebUtils.getLong(request,"userId");
        String businessType = WebUtils.getString(request,"businessType");
        if(placeId != null && StringTools.isNotBlank(businessType) && userId != null) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
                if (physicalStore != null && physicalStore.getUserId().equals(loginUser.getId())) {
                    PlaceProfitUser placeProfitUser = PlaceProfitUserService.self().getByKeys(placeId, userId);
                    if (placeProfitUser != null) {
                        WebUtils.setAttribute(request, placeProfitUser);

                        if (StringTools.isNotBlank(placeProfitUser.getIncomeRatioContent())) {
                            IncomeRatioContent incomeRatioContent = JsonTools.fromJson(placeProfitUser.getIncomeRatioContent(), IncomeRatioContent.class);
                            for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                                if (item.getBusinessType().equals(businessType)) {
                                    request.setAttribute("incomeRatio", item.getIncomeRatio());
                                }
                            }
                        }
                    }
                }
            }
        }
        request.setAttribute("businessTypeName",EBusinessType.note(businessType));
        return "/place/user/business_type/edit.html";
    }

    @Route(value = {"/place/user/business_type/update.do"})
    public AjaxResult doDeviceFuncUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        PlaceProfitUser placeProfitUser = WebUtils.getParameter(request,PlaceProfitUser.class);
        String businessType = WebUtils.getString(request,"businessType");
        Double incomeRatio = WebUtils.getDouble(request,"incomeRatio");
        if(placeProfitUser != null && StringTools.isNotBlank(businessType) && placeProfitUser.getPlaceId() != null && placeProfitUser.getUserId() != null){
            if(incomeRatio == null || incomeRatio < 0 || incomeRatio > 100){
                result.setMsg("请填写正确的分成比例");
                return result;
            }

            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeProfitUser.getPlaceId());
                if (physicalStore != null && physicalStore.getUserId().equals(loginUser.getId())) {
                    PlaceProfitUser profitUserTemp = PlaceProfitUserService.self().getByKeys(placeProfitUser.getPlaceId(), placeProfitUser.getUserId());
                    IncomeRatioContent incomeRatioContent = null;
                    if (StringTools.isNotBlank(profitUserTemp.getIncomeRatioContent())) {
                        incomeRatioContent = JsonTools.fromJson(profitUserTemp.getIncomeRatioContent(), IncomeRatioContent.class);
                    }

                    if (incomeRatioContent == null) {
                        incomeRatioContent = new IncomeRatioContent();
                        IncomeRatioContent.Item item = new IncomeRatioContent.Item();
                        item.setBusinessType(businessType);
                        item.setIncomeRatio(incomeRatio);
                        incomeRatioContent.getItems().add(item);
                    } else {
                        for (IncomeRatioContent.Item item : incomeRatioContent.getItems()) {
                            if (item.getBusinessType().equals(businessType)) {
                                item.setIncomeRatio(incomeRatio);
                            }
                        }
                    }

                    try {
                        if (PlaceProfitUserService.self().updateNotNull(placeProfitUser, incomeRatioContent)) {
                            result.setCode(DtoConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        result.setMsg(e.getMessage());
                    }
                }else {
                    result.setCode(DtoConstants.NOT_POWER,"无权限操作");
                }
            }
        }
        return result;
    }

    @Route(value = {"/place/user/business_type/del.do"})
    public AjaxResult doDeviceFuncDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        Long placeId = WebUtils.getLong(request,"placeId");
        String businessType = WebUtils.getString(request,"businessType");
        Long userId = WebUtils.getLong(request,"userId");
        if(placeId != null && StringTools.isNotBlank(businessType) && userId != null) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if (loginUser != null) {
                PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
                if (physicalStore != null && physicalStore.getUserId().equals(loginUser.getId())) {
                    try {
                        if (PlaceProfitUserService.self().deleteBusinessTypeIncomeRatio(placeId, userId, businessType)) {
                            result.setCode(DtoConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        result.setMsg(e.getMessage());
                    }
                }else {
                    result.setCode(DtoConstants.NOT_POWER,"无权限操作");
                }
            }
        }
        return result;
    }
}
